<?php

class LuastanahController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('lihatFoto','create','update','tabel','graph','drawGraph','downloadGraph','excel'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Luastanah;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Luastanah']))
		{
			$model->attributes=$_POST['Luastanah'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->lt_id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Luastanah']))
		{
			$model->attributes=$_POST['Luastanah'];
			if($model->save())
				//$this->redirect(array('view','id'=>$model->lt_id));
				$this->redirect(array('tabel'));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Luastanah');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Luastanah('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Luastanah']))
			$model->attributes=$_GET['Luastanah'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Luastanah::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='luastanah-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	public function actionTabel()
	{
		$model=new Luastanah('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Luastanah']))
			$model->attributes=$_GET['Luastanah'];

		if(isset($_POST['pilihantahun'])){ 
			$pilihantahun=$_POST['pilihantahun'];
			$luastanah = Luastanah::model()->findAllByAttributes(array('tahun'=>$pilihantahun));
		}else{
			$pilihantahun=0;
		}
			
		$jml_lahanpertanian=0;
		$jml_lahannonpertanian=0;
		$jml_lahantotal=0;
		
		if(!empty($luastanah))
		foreach($luastanah as $lt){
			$jml_lahanpertanian+=$lt->lahanpertanian;
			$jml_lahannonpertanian+=$lt->lahannonpertanian;
			$jml_lahantotal+=$lt->jumlah;
		}
		
		//$this->render('tabel',array(
		//	'model'=>$model,
		//));
		$this->render('tabel',compact('model','pilihantahun','jml_lahanpertanian','jml_lahannonpertanian','jml_lahantotal'));
	}
	public function actionGraph(){
		$this->render('grafik');
	}
	public function actionDrawGraph(){
		$array_tahun = Konstanta::arrayTahun();
		$array_lahanpertanian = array();
		$array_lahannonpertanian = array();
		$array_lahantotal = array();
		foreach($array_tahun as $key=>$tahun){
			$array_lahannonpertanian[$key]=0;
			$array_lahanpertanian[$key]=0;
			$array_lahantotal[$key]=0;
		}
		foreach($array_tahun as $key=>$tahun){
			$luastanah = Luastanah::model()->findAllByAttributes(array('tahun'=>$tahun));
			if(empty($luastanah)) continue;
			foreach($luastanah as $lt){
				$array_lahannonpertanian[$key]+=$lt->lahannonpertanian;
				$array_lahanpertanian[$key]+=$lt->lahanpertanian;
				$array_lahantotal[$key]+=$lt->jumlah;
			}
		}
		
		$DataSet = new pData;
		$DataSet->AddPoint($array_lahannonpertanian,"Serie1");
		$DataSet->AddPoint($array_lahanpertanian,"Serie2");
		$DataSet->AddPoint($array_lahantotal,"Serie3");
 		$DataSet->AddPoint($array_tahun,"labelserie");
 		$DataSet->AddAllSeries();  
 		$DataSet->SetAbsciseLabelSerie("labelserie");  
 		$DataSet->SetSerieName("Lahan Non Pertanian","Serie1");  
 		$DataSet->SetSerieName("Lahan Pertanian","Serie2");
 		$DataSet->SetSerieName("Lahan Total","Serie3");
 		
 		// Initialise the graph     
		 $Test = new pChart(700,230);     
		 $Test->setFontProperties("Fonts/tahoma.ttf",8);     
		 $Test->setGraphArea(70,30,680,200);     
		 $Test->drawFilledRoundedRectangle(7,7,693,223,5,240,240,240);     
		 $Test->drawRoundedRectangle(5,5,695,225,5,230,230,230);     
		 $Test->drawGraphArea(255,255,255,TRUE);  
		 $Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2);     
		 $Test->drawGrid(4,TRUE,230,230,230,50);  
		   
		 // Draw the 0 line     
		 $Test->setFontProperties("Fonts/tahoma.ttf",6);     
		 $Test->drawTreshold(0,143,55,72,TRUE,TRUE);     
		   
		 // Draw the line graph  
		 $Test->drawLineGraph($DataSet->GetData(),$DataSet->GetDataDescription());     
		 $Test->drawPlotGraph($DataSet->GetData(),$DataSet->GetDataDescription(),3,2,255,255,255);     
		   
		 // Finish the graph     
		 $Test->setFontProperties("Fonts/tahoma.ttf",8);     
		 $Test->drawLegend(545,35,$DataSet->GetDataDescription(),255,255,255);     
		 $Test->setFontProperties("Fonts/tahoma.ttf",11);     
		 $Test->drawTitle(150,22,"Grafik Luas Lahan Per Tahun",50,50,50,585);
		 
		 $Test->Render("images/draw.png");
		 $Test->Stroke();
		 exit;
	}
	public function actionDownloadGraph(){
		$file = "images/draw.png";
		if (file_exists($file)) {
			header('Content-Description: File Transfer');
			header('Content-Type: application/octet-stream');
			header('Content-Disposition: attachment; filename='.basename($file));
			header('Content-Transfer-Encoding: binary');
			header('Expires: 0');
			header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
			header('Pragma: public');
			header('Content-Length: ' . filesize($file));
			ob_clean();
			flush();
			readfile($file);
			exit;
		}else throw new CHttpException(404,'The requested files does not exist.');
	}
	public function actionExcel(){
		$model=Luastanah::model()->findAll();
		$printout = "Lahan Pertaninan\tLahan Bukan Pertanian\tJumlah\n";
		foreach($model as $m){
			$printout.=$m->lahanpertanian."\t".$m->lahannonpertanian."\t".$m->jumlah."\n";
		}
		$filename = "luaslahan.xls"; 
		header("Content-Disposition: attachment; filename=\"$filename\""); 
		header("Content-Type: application/vnd.ms-excel"); 
		echo $printout;
		exit;
	}
	public function actionLihatFoto(){
		$ctrl='B1S2';
		$crumbs=array(
			'Geografis'=>array('geografis/index'),
			'Luas Tanah'=>array('luastanah/tabel'),
			'Foto',
		);
		$model=Foto::model()->findAllByAttributes(array('ft_kode'=>$ctrl));
		$this->render('foto',compact('model','ctrl','crumbs'));
	}
}
